<script type='text/javascript' src="../ckeditor4.4.1/ckeditor.js"></script>
<script type="text/javascript" src="../ckeditor4.4.1/adapters/jquery.js"></script>

<div id='dict' class='tree'></div>

<style>
	#edit 
	{
		padding-right: 10px;
	}
	#editform
	{
		margin-bottom: 10px;
	}
	table.params
	{
		width:100%;
		border-collapse:collapse;
	}
	table.params tr td:first-child
	{
		text-align:right;
		white-space:nowrap;
		padding-right: 5px;
		vertical-align: top;
	}
	
	table.params .active td
	{
		background-color: #DEEDF7;
	}
	
	table.params td
	{
		padding: 5px;
		vertical-align:top;
	}
	
	table.params td.v
	{
		width:100%;
		text-align:left;
	}
	table.params td.v input[type=text],
	table.params td.v textarea,
	table.params td.v select {
		width:100%;
	}
	table.params .ro {
		color: gray;
	}
	table.params .file_from_url {
		width: 300px !important;
	}
	.mandatory-sign
	{
		display:inline;
	}
	
	.edit-file
	{
		float:right;
		padding: 5px;
	}
	#dict {
		background-color:white;
	}
</style>

<div class="toolbar ui-widget-header ui-corner-all">
	<button class='editCancel' onclick="edit_cancel()">Отменить</button>
	<button class='editApply' onclick="edit_do('apply')">Применить</button>
	<button class='editSave' onclick="edit_do('save')">Сохранить</button>
</div>	

<form id='editform' method=post enctype='multipart/form-data'>
<input type=hidden name='vid' value='{$view.id}'>
<input type=hidden name='aid' value='{$action.id}'>
<input type=hidden name='do'>
		
<div id="tabs">
	<ul>
		<li><a href="#edit">Поля</a></li>
	</ul>

	<div id='edit'>
		<table class='params'>
			{foreach $action.params as $param}
			<tr>
				<td>
				{if $param.type}
					{if $param.mandatory}<span class="ui-icon ui-icon-notice mandatory-sign">&nbsp;&nbsp;&nbsp;</span>{/if} {$param.title}:
				{/if}
				</td>
				<td class=v>
				{if $param.type}
					{if $param.tree_id || $param.list_id}
						<select name='p[{$param.name}]' {if $param.tree_id}tree_id='{$param.tree_id}'{else}list_id='{$param.list_id}'{/if} title='{$param.title|escape:'quotes'}' class='{if $param.mandatory}mandatory{/if}'>
							<option selected current></option>
							<option value='_choose'>Выбрать...</option>
						</select>
					{else}
						{if $param.type == 'String' || $param.type == 'Integer'}
							<input type=text name='p[{$param.name}]' maxlength='{$param.max_length}' class='{if $param.mandatory}mandatory{/if}' title='{$param.title|escape:'quotes'}'>
						{else if $param.type == 'LongString'}
							<textarea name='p[{$param.name}]' rows=3 class='{if $param.mandatory}mandatory{/if}' title='{$param.title|escape:'quotes'}'>{$param.value}</textarea>
						{else if $param.type == 'Text'}
							<textarea name='p[{$param.name}]' rows=3 class='text {if $param.mandatory}mandatory{/if}'>{$param.value}</textarea>
						{else if $param.type == 'Checkbox'}
							<input type=hidden name='p[{$param.name}]' value='{if $param.value}1{/if}'>
							<input type=checkbox name='{$param.name}' {if $param.value}checked{/if} title='{$param.title|escape:'quotes'}'>
						{else if $param.type == 'Date'}
							<input type=text name='p[{$param.name}]' maxlength='64' class='{if $param.mandatory}mandatory{/if} {if !$param.value}empty{/if}' value='{$param.value|default:'ГГГГ-ММ-ДД'}' emptyval='ГГГГ-ММ-ДД'>
						{else if $param.type == 'File'}
							<input type=file name='{$param.name}' class='{if $param.mandatory}mandatory{/if}' />
							<input type=text name='URL[{$param.name}]' class='file_from_url' data-fname='{$param.name}' />
							<input type=hidden name='p[{$param.name}]' value='{$param.value}' data-fname='{$param.name}' />
							{if $param.value}
								<div class='edit-file ui-widget-content ui-corner-all' data-fname='{$param.name}'>
									<a id='{$param.name}' href='/{$param.value}' title='/{$param.value}' target=_blank>
										{if $param.is_image}<img src='{thumbnail width=100 height=100}{$smarty.server.DOCUMENT_ROOT}/{$param.value}{/thumbnail}'/>{else}/{$param.value}{/if}
									</a>
									<br>
									<input type=checkbox class='delete-file' onclick="delFile('{$param.name}',this.checked);"> Удалить
								</div>
							{/if}
						{else if $param.type == 'Readonly'}
							<input type=hidden name='p[{$param.name}]'>
							<span class='ro'>{$param.value}</span>
						{else if $param.type == 'Display'}
							{$param.value}
						{else}
							<span>{$param.name} - Invalid type</span>
						{/if}
					{/if}
				{else}
					<input type=hidden name='p[{$param.name}]' value='{$param.value}'>
				{/if}
				</td>
			</tr>
			{/foreach}
		</table>
		<span class="ui-icon ui-icon-notice mandatory-sign">&nbsp;&nbsp;&nbsp;</span> - Поля, обязательные для заполнения
	</div>
</div>

</form>

<div class="toolbar ui-widget-header ui-corner-all">
	<button class='editCancel' onclick="edit_cancel()">Отменить</button>
	<button class='editApply' onclick="edit_do('apply')">Применить</button>
	<button class='editSave' onclick="edit_do('save')">Сохранить</button>
</div>	

<script>
	function addTab(id, title) {
		$('#tabs').append( $('#'+id) );
		$('#tabs ul').append( $('<li>').append($('<a>').attr('href','#'+id).html(title)) );
		$('#tabs').tabs('refresh');
	}
	
	function setFirstTabTitle(title) {
		$('#tabs .ui-tabs-nav li:first a').html(title);
	}
	
	function createTabs() {}
	
	var k = {$k};
	
	$( function() {
		$('#tabs').tabs();
		createTabs();
		if ($('#tabs > .ui-tabs-panel').length <= 1) {
			$('#tabs .ui-tabs-nav').hide();
		} else {
			$('#tabs').tabs('option','active',{$goTab});
		}
		
		{foreach $action.params as $param}
			{if $param.dict_value}
				setDictVal($("#editform select[name='p[{$param.name}]']"), '{$param.value|escape:quotes}', '{$param.dict_value|escape:quotes}');
			{elseif $param.type == 'String' || $param.type == 'Integer'}
				$("#editform input[name='p[{$param.name}]']").val('{$param.value|escape:quotes}');
			{elseif $param.type == 'Date'}
				$("#editform input[name='p[{$param.name}]']").datepicker( { dateFormat: 'yy-mm-dd' } );
			{/if}
		{/foreach}

		$('#edit .empty').on( {
			'focus': function() { 
				if ($(this).hasClass('empty')) { 
					$(this).val(''); 
				}; 
				$(this).removeClass('empty'); 
			}
		} );

		$('#editform').on( {
			'submit': function(e) {
				$("#editform .mandatory").each( function(i) {
					if (!$(this).val() || $(this).hasClass('empty')) {
						if ($(this).is('input:file')) 
						{
							if ($('#editform input[data-fname='+$(this).attr('name')+']').val() && 
								$('#editform .edit-file[data-fname='+$(this).attr('name')+'] .delete-file:not(:checked)').length) 
							{
								return true;  //keep current file
							}
							if ($('#editform .file_from_url[data-fname='+$(this).attr('name')+']').val()) {
								return true; //load file from url
							}
						}
						var f = $(this);
						e.preventDefault();
						errBox('Не все обязательные поля заполнены!',function() { f.focus(); } );
						$('.toolbar button').attr('disabled',false);
					}
				} );
				$("#editform .empty").each( function(i) {
					$(this).val('');
				} );
			}
		} );
		
		$('#edit :checkbox').click(function() {
			$("#edit input[name='p["+$(this).attr('name')+"]']").val( $(this).is(':checked')?'1':null );
		});
		
		$('#edit :file').change(function(){
			$('#edit .file_from_url[data-fname='+$(this).attr('name')+']').toggle($(this).val());
		});
		$('#edit .file_from_url').keyup(function(){
			$('#edit :file[name='+$(this).attr('data-fname')+']').toggle(!Boolean($(this).val()));
		});

		CKEDITOR.on('instanceReady', function(e) {
			e.editor.on('focus',function(e) {  $('#edit textarea[name="'+e.editor.name+'"]').closest('tr').addClass('active'); } );
			e.editor.on('blur',function(e) { $('#edit textarea[name="'+e.editor.name+'"]').closest('tr').removeClass('active');  } );
		} );
		
		$('#edit textarea.text').each( function() {
			$(this).ckeditor( {
				filebrowserUploadUrl: '../file_upload.php',
				filebrowserImageUploadUrl: '../file_upload.php'
			} );
		} );
		
		$('table.params input:text, input:file, textarea, :checkbox, select').on( {
			'focus': function(e) { $(e.target).closest('tr').addClass('active'); },
			'blur': function(e) { $(e.target).closest('tr').removeClass('active'); }
		} );
		
//		var editor = $(this).ckeditorGet();  http://ckeditor.com/blog/CKEditor_for_jQuery

		$('.editCancel').button( {
			text: 'Отменить',
			icons: {
				primary: "ui-icon-closethick"
			}
		} ); 
		
		$('.editApply').button( {
			text: 'Применить',
			icons: {
				primary: "ui-icon-transferthick-e-w"
			}
		} ); 
		
		$('.editSave').button( {
			text: 'Сохранить',
			icons: {
				primary: "ui-icon-disk"
			}
		} ); 
		
		// Dictionaries
		$('#edit select').on( {
			'change': function(e) {
				if ($(this).val() != '_choose') {
					return;
				}
				openDict(
					$(e.target).attr('tree_id') ? $(e.target).attr('tree_id') : $(e.target).attr('list_id'),
					Boolean($(e.target).attr('tree_id')),
					$(e.target).attr('title'),
					function(target){
						return function(id,name){ setDictVal(target,id,name); };
					}($(e.target)),
					function(target) {
						return function(){ target.children('option[current]').attr('selected',true); };
					}($(e.target))
				);
			}
		} );
	} );
	
	function openDict(viewId, isTree, title, onSelect, onClose) {
		$('#dict').html('');
		var showDict = function(title, onClose) {
			$('#dict').dialog({
				modal: true,
				minWidth: 400,
				buttons: { "Закрыть": function(){ $(this).dialog('close'); } },
				open: function(e){ $(e.target).dialog('option', 'title', title); },
				close: function(){ onClose(); } 
			});
		};
		
		if (isTree) {
			call('admin.getTree',{ 'id':viewId }).done(function(items){
				$('#dict').tree({
					'items': items,
					onclick: function(el){ 
						$('#dict').dialog("close");
						onSelect(el.attr('data-id'), el.attr('data-name')); 
						return false;
					},
					expand: 'top'
				})
				showDict(title, onClose);
			} );			
		} else {
			var dictGrid = new Grid($('#dict'), viewId, {
				brief: true,
				onReady: function(grid) { showDict(title, onClose); }
			} );
			dictGrid.onClick = function(id, oTD) {
				$('#dict').dialog("close");
				onSelect(id, oTD.html());
			};		
		}
	}
	
	function setDictVal(oSel, id, name)
	{
		oSel.children('option[current]').html(name).val(id);
		if (id && !oSel.hasClass('mandatory') && oSel.children('option').length<3) {
			oSel.prepend("<option value=''>");
		}
		oSel.children('option').attr('selected',false);
		oSel.children('option[current]').attr('selected',true);
		oSel.trigger('dictValChange',id);
	}
	
	function delFile(pnm, del)
	{
		if (del) {
			$("#editform input[name='p["+pnm+"]']").val( '\t'+$("#editform input[name='p["+pnm+"]']").val() );
		} else {
			$("#editform input[name='p["+pnm+"]']").val( $("#editform input[name='p["+pnm+"]']").val().slice(1) );
		}
	}

	function edit_cancel()
	{
		location.href='{$referer}';
	}
	
	function edit_do(op)
	{
		$('.toolbar button').attr('disabled',true);
		$('#editform input[name=do]').val(op);
		$('#editform').submit();
	}
</script>